package com.nega.modules.service.impl;

import com.nega.commons.constant.ConstantUtil;
import com.nega.commons.email.EmailData;
import com.nega.commons.model.MemberUser;
import com.nega.commons.util.DataUtil;
import com.nega.commons.util.RSAUtils;
import com.nega.modules.mapper.MemberUserMapper;
import com.nega.modules.service.MailCoreService;
import com.nega.modules.service.MemberUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: Garcia
 * @CreateDate: 2019/5/17 23:24
 * @Description: what it is class？
 */
@Service
@Slf4j
public class MemberUserServiceImpl implements MemberUserService {

    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private MailCoreService mailCoreService;

    @Override
    public MemberUser getUserById(String id) {
        return memberUserMapper.getUserById(id);
    }

    @Override
    public MemberUser getUserByAccount(String account) {
        return memberUserMapper.getUserByAccount(account);
    }

    @Override
    public MemberUser getUserByEmail(String email) {
        return memberUserMapper.getUserByEmail(email);
    }

    @Override
    public MemberUser getUserByMobile(String mobile) {
        return memberUserMapper.getUserByMobile(mobile);
    }

    @Override
    public MemberUser getUserByInstituion(String instituionCode) {
        return memberUserMapper.getUserByInstituion(instituionCode);
    }

    @Override
    public void insert(MemberUser user) {
        if (user == null){
            return;
        }

        MemberUser memberUser = memberUserMapper.getNotActiveUserByEmail(user.getEmail());
        if (memberUser==null){
            StringBuilder sb = new StringBuilder();
            if (user.getType() == 0){
                sb.append("PER-").append(DataUtil.getRandomData(5));
            }else {
                sb.append("CORP-").append(DataUtil.getRandomData(5));
            }
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            user.setStatus(false);
            user.setIsVip(false);
            user.setUserCode(sb.toString());
            user.setCreateTime(new Date());
            user.setUpdateTime(user.getCreateTime());
            memberUserMapper.insert(user);
        }else {
            memberUser.setName(user.getName());
            memberUser.setCompanyName(user.getCompanyName());
            memberUser.setCompanyPhone(user.getCompanyPhone());
            memberUser.setInstituionCode(user.getInstituionCode());
            memberUser.setInvitationCode(user.getInvitationCode());
            memberUser.setMobile(user.getMobile());
            memberUser.setType(user.getType());
            memberUser.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            memberUser.setCreateTime(new Date());
            memberUser.setUpdateTime(user.getCreateTime());
            memberUserMapper.update(memberUser);
        }

        log.info("注册激活邮件发送>>>>");

        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String data =  RSAUtils.encryptByPrivateKey(user.getEmail()+"-"+System.currentTimeMillis(), ConstantUtil.PRIVATE_KEY);
                    String url = "localhost:8081/mem/active?token="+data;
                    EmailData emailData = new EmailData();
                    emailData.setRecipient(user.getEmail());
                    emailData.setSubject("账户激活");
                    emailData.setContent("<html><head></head><body><div>感谢您注册使用舆情系统。</div><br><br><div>您的登录账号为："+emailData.getRecipient()+"</div><br><br><h3>此邮件为官方激活邮件！请点击下面链接完成激活操作！</h3><div><a href='"+url+"' style='text-decoration: underline;'>"+url+"<a/></div><div>(此链接将于24小时后失效，请尽快激活邮箱。)</div><br><br><div>如果以上链接无法访问，请将该网址复制并粘贴至新的浏览器窗口中。</div><div>如果你错误地收到了此电子邮件，你无需执行任何操作来注销帐号！此帐号将不会被激活。</div><div>该邮件由系统自动发送，请不要直接回复。</div></body></html>");
                    mailCoreService.sendEmail(emailData);
                } catch (Exception e) {
                    log.error("加密异常",e);
                }
            }
        });
        executorService.shutdown();
    }

    @Override
    public void activeUserByEmail(String email) {
        memberUserMapper.activeUserByEmail(email);
    }

    @Override
    public MemberUser getUserByUserCode(String invitationCode) {
        return memberUserMapper.getUserByUserCode(invitationCode);
    }

    @Override
    public void updateInvitaNumberByEmail(String email, int num) {
        memberUserMapper.updateInvitaNumberByEmail(email,num);
    }
}
